package hn.cch.grammar.net.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;


public class Server {
    private DatagramSocket server;
    private DatagramPacket dp;
    private int port;

    public Server() {
        port = 8080;
        try {
            server = new DatagramSocket(port);
            System.out.println("服务端启动：" + server);
        } catch (SocketException e) {
            System.out.println(e.getMessage());
        }

    }

    public static void main(String[] args) {

        Server server = new Server();
        while (true) {
            server.receive();
            server.send();
        }
    }


    public void receive() {

        try {
            //接收
            byte[] buf = new byte[1024];
            dp = new DatagramPacket(buf, buf.length);
            server.receive(dp);
            String str = new String(dp.getData(), 0, dp.getLength());
            System.out.println(dp.getAddress() + ":" + dp.getPort() + "：" + str);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    public void send() {
        //while (true) {
        //    //发送
        //    System.out.println("输入发送内容（为空断开连接）：");
        //    //控制台输入
        //    Scanner scanner = new Scanner(System.in);
        //    String str = scanner.nextLine();
        //    //为空退出
        //    if (str.equals("")) {
        //        break;
        //    }
        //
        //    byte[] buf = str.getBytes();
        //    try {
        //        server.send(new DatagramPacket(buf, buf.length, dp.getAddress(), dp.getPort()));
        //    } catch (IOException e) {
        //        System.out.println(e.getMessage());
        //    }
        //}

        String str = "----------";
        System.out.println("发送内容：" + str);
        byte[] buf = str.getBytes();
        try {
            server.send(new DatagramPacket(buf, buf.length, dp.getAddress(), dp.getPort()));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}
